package com.smart.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smart.filter.JwAuthenticationTokenFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    PasswordEncoder passwordEncoder() {
        //使用明文密码：为了简单方便测试
        return NoOpPasswordEncoder.getInstance();
        //暗文密码：会用salt加密
        // return new BCryptPasswordEncoder();
    }

    @Autowired
    JwAuthenticationTokenFilter jwAuthenticationTokenFilter;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        //设置注入的自定义认证实现类userService，必须实现了UserDetailsService接口
////        auth.userDetailsService(userDetailsService);
//    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
//                关闭csrf
                .csrf().disable()
//                不tong过session获取secruitycontext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //对于登录接口允许匿名访问
                .antMatchers("/api/login").permitAll()
                .antMatchers("/api/user/login").permitAll()
                .antMatchers("/api/user/a").permitAll()
                .antMatchers("/api/**").permitAll()
//                除了上面所有请求全部需要鉴权认证
                .anyRequest().authenticated();


        http.addFilterBefore(jwAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
